package com.jsz.peini.server.thread;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserSms;
import com.jsz.peini.bean.user.UserSmsExample;
import com.jsz.peini.common.util.AppPush;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.SmsSendUtil;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.mapper.coupon.CouponInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.mapper.user.UserSmsMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.util.FansNotifyRedisUtil;


public class FansAndCouponNotifyThread extends Thread{
	
	Logger logger = Logger.getLogger(FansAndCouponNotifyThread.class);
	
	public void init(){
		this.start();
	}
	
	@Override
	public void run() {
		super.run();
		
		CouponInfoMapper couponInfoMapper = (CouponInfoMapper)SpringContextUtil.getBean(CouponInfoMapper.class);
		UserSmsMapper userSmsMapper = (UserSmsMapper)SpringContextUtil.getBean(UserSmsMapper.class);
		UserInfoMapper userInfoMapper = (UserInfoMapper)SpringContextUtil.getBean(UserInfoMapper.class);
		
		while(true)
		{
			try {
				List<String> list = RedisUtil.brpop(RedisConstants.FANS_NITIFY_THREAD);
				if(list.size() > 1){
					String userId = list.get(1);
					
					//查询要过期的优惠券
					Date cstart = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd")+ " 00:00:00", "yyyy-MM-dd hh:mm:ss");
					Calendar now = Calendar.getInstance();
					now.set(Calendar.DATE, now.get(Calendar.DATE) + 2);
					Date cend = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(now.getTime(), "yyyy-MM-dd")+ " 00:00:00", "yyyy-MM-dd hh:mm:ss");
					HashMap<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("userId", userId);
					paramMap.put("startTime", cstart);
					paramMap.put("endTime", cend);
					List<HashMap<String, Object>> cList = couponInfoMapper.getMyCouponInfo(paramMap);
					if(cList.size() > 0){//没有不退送消息
						//查询消息表今天是否已经推送过消息
						UserSmsExample smsExample = new UserSmsExample();
						Date start = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd")+ " 00:00:00", "yyyy-MM-dd hh:mm:ss");
						Date end = DateTimeUtils.formatString2Date(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd")+ " 23:59:59", "yyyy-MM-dd hh:mm:ss");
						smsExample.createCriteria()
							.andToidEqualTo(userId)
							.andSendtimeBetween(start, end)
							.andSmstypeEqualTo(3);
						int smsCnt = userSmsMapper.countByExample(smsExample);
						if(smsCnt == 0){
							UserSms userSms = new UserSms();
							userSms.setSmsid(UUID.randomUUID().toString().replace("-", ""));
							userSms.setIsremind(1);
							userSms.setReceivdel(0);
							userSms.setSenddel(0);
							userSms.setSendtime(new Date());
							userSms.setSmscontent("您有"+cList.size()+"张优惠券即将过期！");
							userSms.setSmstype(3);
							userSms.setToid(userId);
							userSmsMapper.insertSelective(userSms);
							
							
							//个推发送消息
							JSONObject object = new JSONObject();
					        object.put("title", "系统消息");
					        object.put("content", "您有"+cList.size()+"张优惠券即将过期！");
					        object.put("type", 3);
					        object.put("paramId", "");
					        
					        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
					        AppPush.sendPush(object,userInfo.getUserPhone().split(","));
						}
					}
					
					//查询今天是否需要提醒
					boolean flag = FansNotifyRedisUtil.ifRemind(userId);
					
					if(flag == true){
						Date date = FansNotifyRedisUtil.getLastSignRemind(userId);
						Date nowD = new Date();
						
						UserSmsExample example = new UserSmsExample();
						if(date != null){
							example.createCriteria().andToidEqualTo(userId).andSmstypeEqualTo(9).andSendtimeBetween(date, nowD);
						}else{
							example.createCriteria().andToidEqualTo(userId).andSmstypeEqualTo(9).andSendtimeLessThanOrEqualTo(nowD);
						}
						
						int cnt = userSmsMapper.countByExample(example);
						if(cnt > 0){
							UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
							
							JSONObject object = new JSONObject();
							object.put("title", "系统消息");
							object.put("content", "致充满魅力的您，在您离开的这段时间，又有"+cnt+"人偷偷地关注了您，快去看看吧~");
							object.put("paramId", null);
							object.put("type", 208);
							AppPush.sendPush(object,userInfo.getUserPhone().split(","));
							
							SmsSendUtil.sendSmsFit(null, userId, null, 208, "致充满魅力的您，在您离开的这段时间，又有"+cnt+"人偷偷地关注了您，快去看看吧~");
						}
						
						FansNotifyRedisUtil.updateLastSignRemind(userId, nowD);
					}
				}
				
				Thread.sleep(1);
			} catch (Exception e1) {
				e1.printStackTrace();
				logger.info("fail", e1);
			}
		}
		
	}
	
}